package com.huaxia.util;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpRequestUtil {

    private static final Logger log = LoggerFactory.getLogger(HttpRequestUtil.class);
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        return HttpRequestUtil.httpRequest(requestUrl, requestMethod, outputStr, new ArrayList<>());
    }
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr, List<Map<String,String>> headers) {
        StringBuffer buffer = new StringBuffer();
        InputStream inputStream = null;
        String result = null;
        try {
            // System.out.println("requestUrl="+requestUrl);
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            httpUrlConn.setRequestMethod(requestMethod);
            for (Map<String,String> header:headers){
                log.info(header.get("key")+":"+header.get("value"));
                httpUrlConn.setRequestProperty(header.get("key"),header.get("value"));
            }
            if ("GET".equalsIgnoreCase(requestMethod)) {
                httpUrlConn.connect();
            }
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();

                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();

            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();

            result = buffer.toString();
            return JSONObject.fromObject(result);
        } catch (ConnectException ce) {
            ce.printStackTrace();
            log.error("http request error:{}", ce);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("http request error:{}", e);
        } finally {
            try {
                log.info("requestUrl:{}:outputStr:{}:result:{}",requestUrl,outputStr,result);
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
